#pragma once
//
//  allocator.hpp
//  JanMalloc
//
//  Created by janhit on 2022/4/16.
//

#ifndef allocator_hpp
#define allocator_hpp

#include "TypesDef.hpp"
#include "../Concurrency/SpinLock.hpp"
#include <set>
#include <list>


namespace MMFAlloc{


class MemoryItem;

struct Allocator
{
    friend class ThreadAllocator;
    
private:
    
    const u32 mBlockSize;
    const u64 mInitialSize;
    u64 mCapacity;
    
    time_t mCreateTime;
    time_t mLastAccessTime;
    
    const std::thread::id& mThradId;
    MMF::SpinLock mLock;
    
    std::set<MemoryItem*> mInUse;
    std::list<MemoryItem*> mFree;
    
public:
    
    Allocator(u64 capacity, u32 blockSize, const std::thread::id& thdId);
    ~Allocator();
    
    u32 BlockSize();
    u64 Capacity();
    
    void* Alloc();
    void Free(void* addr);
    
private:
    
    MemoryItem* AllocItem();
    void Sharink();
    void Grow();
};

}

#endif /* allocator_hpp */
